package dao;

import entity.User;
import util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
    public List<User> findAll(){
        List<User> cts=new ArrayList<>();
        ResultSet rs= DBUtil.find("SELECT * FROM \"USER\"");
        ResultSetToList(cts, rs);
        return cts;
    }

    private void ResultSetToList(List<User> cts, ResultSet rs) {
        try {
            while(rs.next()){
                User c=new User();
                c.setBh(rs.getString(1));
                c.setName(rs.getString(2));
                c.setPwd(rs.getString(3));
                c.setPhone(rs.getString(4));
                c.setImg(rs.getString(5));
                cts.add(c);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<User> findByName(String name){
        String sql="SELECT * FROM \"USER\" where name like ?";
        List<User> cts=new ArrayList<>();
        ResultSet rs= DBUtil.find(sql,name);
        ResultSetToList(cts, rs);
        return cts;
    }

    public void save(User u){
        String sql="INSERT into \"USER\" values(?,?,?,?,?)";
        DBUtil.insert(sql,u.toArray());
    }
}
